package com.rightsidetech.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.mall.dto.request.DetailSpecsNameReq;
import com.rightsidetech.mall.dto.request.DetailSpecsReq;
import com.rightsidetech.mall.dto.request.DetailSpecsValueReq;
import com.rightsidetech.mall.dto.request.gift.GiftPageReq;
import com.rightsidetech.mall.dto.request.gift.SaveGiftReq;
import com.rightsidetech.mall.dto.request.gift.UpdateGiftReq;
import com.rightsidetech.mall.dto.response.gift.ActGiftCommodityResp;
import com.rightsidetech.mall.dto.response.gift.GiftDetailResp;
import com.rightsidetech.mall.dto.response.gift.GiftPageResp;
import com.rightsidetech.mall.entity.MallBaseInfoWithBLOBs;
import com.rightsidetech.mall.entity.MallBrand;
import com.rightsidetech.mall.entity.MallGiftCommodity;
import com.rightsidetech.mall.entity.MallType;
import com.rightsidetech.mall.mapper.MallBaseInfoMapper;
import com.rightsidetech.mall.mapper.MallBrandMapper;
import com.rightsidetech.mall.mapper.MallGiftCommodityMapper;
import com.rightsidetech.mall.mapper.MallTypeMapper;
import com.rightsidetech.mall.service.MallGiftCommodityService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("mallGiftCommodityService")
public class MallGiftCommodityServiceImpl implements MallGiftCommodityService {

    @Resource
    private MallGiftCommodityMapper mallGiftCommodityMapper;
    @Resource
    private MallBaseInfoMapper mallBaseInfoMapper;
    @Resource
    private MallTypeMapper mallTypeMapper;
    @Resource
    private MallBrandMapper mallBrandMapper;

    @Override
    public ResponseData saveGift(SaveGiftReq req,String createrName,Long createrId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallBaseInfoWithBLOBs baseInfo = mallBaseInfoMapper.selectByPrimaryKey(req.getMallBaseId());
        if(ObjectUtil.isEmpty(baseInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到基础商品");
        }
        DetailSpecsReq specs = req.getSpecs();
        if (ObjectUtil.isEmpty(specs)) {
            if(StrUtil.isNotEmpty(baseInfo.getSpecsJson())){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此基础商品有规格请选择规格后创建换购商品");
            }
            Long count = mallGiftCommodityMapper.selectCountByInfoIdAndSpecs(baseInfo.getId(),null);
            if(count > 0){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此基础商品已经维护过换购商品");
            }
            MallGiftCommodity record = getMallGiftCommodity(req,createrName,createrId,baseInfo);
            if (mallGiftCommodityMapper.insertSelective(record) <= 0) {
                return ResponseData.fail("创建失败");
            }
            return ResponseData.success(CodeIdEnum.Success);
        }
        ResponseData data = checkSpecs(specs);
        if(data != null){
            return data;
        }
        String specs1 = specs.getValueList().stream().map(DetailSpecsValueReq::getSpecsValue).collect(Collectors.joining("、"));
        Long count = mallGiftCommodityMapper.selectCountByInfoIdAndSpecs(baseInfo.getId(),specs1);
        if(count > 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此规格已经维护过积分商品");
        }
        MallGiftCommodity giftCommodity = getMallGiftCommodity(req, createrName, createrId, baseInfo);
        giftCommodity.setSpecsCode(specs.getCode());
        giftCommodity.setSpecsJson(JSONUtil.toJsonStr(specs));
        giftCommodity.setSpecs(specs1);
        if (mallGiftCommodityMapper.insertSelective(giftCommodity) <= 0) {
            return ResponseData.fail("创建失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    private MallGiftCommodity getMallGiftCommodity(SaveGiftReq req,String createrName,Long createrId,MallBaseInfoWithBLOBs baseInfo){
        MallGiftCommodity record = new MallGiftCommodity();
        record.setBaseInfoId(baseInfo.getId());
        record.setPrice(req.getPrice());
        record.setUnderlinedPrice(req.getUnderlinedPrice());
        record.setCommodityName(baseInfo.getCommodityName());
        record.setBrandId(baseInfo.getBrandId());
        record.setTypeId(baseInfo.getTypeId());
        record.setGiftType(req.getGiftType());
        record.setCover(req.getCover());
        record.setCreatedAt(new Date());
        record.setCreaterName(createrName);
        record.setCreaterId(createrId);
        record.setCode(baseInfo.getCode());
        return record;
    }

    @Override
    public ResponseData<PageInfo<GiftPageResp>> page(GiftPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<GiftPageResp> result = mallGiftCommodityMapper.selectPageList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    private ResponseData checkSpecs(DetailSpecsReq specs){
        ConstraintViolation validate = BeanValidator.validate(specs);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<DetailSpecsValueReq> valueList = specs.getValueList();
        List<DetailSpecsNameReq> nameList = specs.getNameList();
        if(nameList.size() != valueList.size()){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格名称与规格值数量不一致");
        }
        for (int i = 0; i < valueList.size(); i++) {
            DetailSpecsNameReq nameReq = nameList.get(i);
            DetailSpecsValueReq valueReq = valueList.get(i);
            ConstraintViolation validate1 = BeanValidator.validate(nameReq);
            if (validate1 != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate1.getMessage());
            }
            ConstraintViolation validate2 = BeanValidator.validate(valueReq);
            if (validate2 != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate2.getMessage());
            }
        }
        return null;
    }

    @Override
    public ResponseData update(UpdateGiftReq req, String updaterName, Long updaterId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallGiftCommodity commodity = mallGiftCommodityMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(commodity)) {
            return ResponseData.fail("未找到需要修改的换购商品");
        }
        MallBaseInfoWithBLOBs info = mallBaseInfoMapper.selectByPrimaryKey(commodity.getBaseInfoId());
        if(ObjectUtil.isEmpty(info)){
            return ResponseData.fail("未找到基础商品");
        }
        DetailSpecsReq specs = req.getSpecs();
        if(ObjectUtil.isEmpty(specs)){
            if(StrUtil.isNotBlank(info.getSpecsJson())){
                return ResponseData.fail("此基础商品有规格，选择规格后编辑");
            }
            MallGiftCommodity record = getMallGiftCommodity(req, null, null, info);
            record.setId(req.getId());
            record.setUpdatedAt(new Date());
            record.setUpdaterId(updaterId);
            record.setUpdaterName(updaterName);
            if (mallGiftCommodityMapper.updateByPrimaryKeySelective(record) <= 0) {
                return ResponseData.fail("操作失败");
            }
            return ResponseData.success(CodeIdEnum.Success);
        }
        ResponseData data = checkSpecs(specs);
        if(data != null){
            return data;
        }
        String specsStr = specs.getValueList().stream().map(DetailSpecsValueReq::getSpecsValue).collect(Collectors.joining("、"));
        if(!specsStr.equals(commodity.getSpecs())){
            Long count = mallGiftCommodityMapper.selectCountByInfoIdAndSpecs(info.getId(), specsStr);
            if(count > 0){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此规格已经维护过换购商品不可重复维护");
            }
        }
        MallGiftCommodity record = getMallGiftCommodity(req, null, null, info);
        record.setSpecsJson(JSONUtil.toJsonStr(specs));
        record.setSpecs(specsStr);
        record.setId(req.getId());
        record.setUpdatedAt(new Date());
        record.setUpdaterId(updaterId);
        record.setUpdaterName(updaterName);
        if (mallGiftCommodityMapper.updateByPrimaryKeySelective(record) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<GiftDetailResp> detail(Long id) {
        if(id == null || id < 1){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"id不可为空或小于1");
        }
        GiftDetailResp result = mallGiftCommodityMapper.selectDetail(id);
        if(ObjectUtil.isEmpty(result)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"没有找到数据");
        }
        MallType mallType = mallTypeMapper.selectByPrimaryKey(result.getTypeId());
        List<Long> typeIds = new ArrayList<>();
        typeIds.add(result.getTypeId());
        if(ObjectUtil.isNotEmpty(mallType)){
            String typeName = mallType.getTypeName();
            while (mallType.getParentId() != 0){
                MallType type = mallTypeMapper.selectByPrimaryKey(mallType.getParentId());
                typeIds.add(type.getId());
                typeName = type.getTypeName() + "/" + typeName;
                mallType = type;
            }
            result.setTypeName(typeName);
        }
        result.setTypeIds(typeIds);
        result.setSpecs(JSONUtil.toBean(result.getSpecsJson(),DetailSpecsReq.class));
        return ResponseData.success(result);
    }

    @Override
    public ActGiftCommodityResp selectActGiftById(Long id) {
        return mallGiftCommodityMapper.selectActGiftById(id);
    }

    @Override
    public List<MallGiftCommodity> selectByIds(List<Long> ids) {
        return mallGiftCommodityMapper.selectByPrimaryKeyList(ids);
    }

    @Override
    public MallGiftCommodity selectTypeIdByGiftId(Long id) {
        return mallGiftCommodityMapper.selectByPrimaryKey(id);
    }

    @Override
    public MallBrand findByBrandName(Long brandId) {
        return mallBrandMapper.selectByPrimaryKey(brandId);
    }

    @Override
    public MallType findByTypeName(Long typeId) {
        return mallTypeMapper.selectByPrimaryKey(typeId);
    }
}
